package com.didi.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.didi.gulimall.api.MemberApiService;
import com.didi.gulimall.common.constant.BizCodeEnume;
import com.didi.gulimall.common.utils.PageUtils;
import com.didi.gulimall.common.utils.Query;
import com.didi.gulimall.common.utils.R;
import com.didi.gulimall.ware.dao.WareInfoDao;
import com.didi.gulimall.ware.entity.WareInfoEntity;
import com.didi.gulimall.ware.service.WareInfoService;
import com.didi.gulimall.ware.vo.FareVo;
import com.didi.gulimall.ware.vo.MemberAddressVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;


/**
 * @author 10626
 */
@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {
    @Autowired
    private MemberApiService memberApiService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.eq("id", key)
                    .or().like("name", key)
                    .or().like("address", key)
                    .or().like("areacode", key);
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public R getFare(Long addrId) {
        R info = memberApiService.info(addrId);
        if (info.getCode() != 0) {
            return info;
        }
        MemberAddressVo address = info.getData("address", new TypeReference<MemberAddressVo>() {
        });
        if (address == null) {
            return R.error(BizCodeEnume.ADDRESS_IS_ABNORMAL.getMsg());
        }
        FareVo fareVo = new FareVo();
        String phone = address.getPhone();
        String substring = phone.substring(phone.length() - 1, phone.length());
        fareVo.setFare(new BigDecimal(substring));
        fareVo.setAddress(address);
        return R.ok().put("data", fareVo);
    }

}